<template>
  <div class="l-rblock">
    <div v-show="steps(0)" class="l-rblock" style="padding: 24px">
      <div class="l-page-panel">
        <el-form :model="formData" :rules="rules" size="mini" ref="baseInfo" label-width="80px">
          <el-col :span="24">
            <el-form-item label="编号" prop="f_Code">
              <el-input v-model="formData.f_Code">
                <el-button slot="append" @click="createUUID">生成UUID</el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="名称" prop="f_Name">
              <el-input v-model="formData.f_Name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图标" prop="f_Icon">
              <l-input-icon :iconList="lr_icons" v-model="formData.f_Icon"> </l-input-icon>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="表单选择" prop="f_FormCode">
              <l-custmerform-select v-model="formData.f_FormCode" @change="custmerformChange" placeholder="请选择">
              </l-custmerform-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="表单版本" prop="f_FormVerison">
              <l-select v-model="formData.f_FormVerison" :options="formVerisons" placeholder="请选择"> </l-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上级" prop="f_PModuleId">
              <l-tree-select v-model="formData.f_PModuleId" :options="modulesExpandTree"> </l-tree-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="排序" prop="f_SortCode">
              <el-input-number v-model="formData.f_SortCode" controls-position="right" :min="1"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态">
              <el-switch :active-value="1" :inactive-value="0" v-model="formData.f_EnabledMark"> </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="f_Description">
              <el-input type="textarea" v-model="formData.f_Description"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </div>
    </div>
    <div v-show="steps(1)" class="l-rblock">
      <l-layout class="l-tab-page">
        <l-panel>
          <div class="l-auto-window">
            <el-tabs v-model="pageActiveName" :stretch="true">
              <el-tab-pane :label="$t('布局设置')" name="tab01">
                <webcode-layout></webcode-layout>
              </el-tab-pane>
              <el-tab-pane v-if="config.layoutType == 2" :label="$t('左侧树形设置')" name="tab05">
                <webcode-lefttree :colslist="colslist"></webcode-lefttree>
              </el-tab-pane>
              <el-tab-pane :label="$t('列表设置')" name="tab02">
                <webcode-columns
                  ref="columnsOp"
                  :tableFields="tableFields"
                  :columnsTree="columnsTree"
                ></webcode-columns>
              </el-tab-pane>
              <el-tab-pane :label="$t('查询设置')" name="tab03">
                <webcode-query ref="queryOp" :queryTree="queryTree"></webcode-query>
              </el-tab-pane>
              <el-tab-pane :label="$t('按钮设置')" name="tab04">
                <webcode-btns :formType="formScheme && formScheme.formType == 1 ? 1 : 0" ref="btnOp"></webcode-btns>
              </el-tab-pane>
            </el-tabs>
          </div>
        </l-panel>
      </l-layout>
    </div>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import { v4 as uuidv4 } from "uuid";
const api = window.$api.custmerForm.scheme;

import webcodeLayout from "./config/layout";
import webcodeLefttree from "./config/leftTree";
import webcodeColumns from "./config/columns";
import webcodeQuery from "./config/query";
import webcodeBtns from "./config/btns";

export default {
  provide() {
    return {
      formConfig: this.config,
    };
  },
  props: {
    stepActive: {
      type: Number,
      default: 0,
    },
  },
  components: {
    webcodeLayout,
    webcodeLefttree,
    webcodeColumns,
    webcodeQuery,
    webcodeBtns,
  },
  data() {
    return {
      tableFields: [],
      pageActiveName: "tab01",
      columnsTree: [
        {
          label: "全选",
          children: [],
        },
      ],
      queryTree: [
        {
          label: "全选",
          children: [],
        },
      ],
      colslist: [],
      config: {
        layoutType: 1,
        queryType: "1",
        btns: [
          { label: "新增", id: "Add", prop: "Add", icon: "el-icon-plus", isRowBtn: false },
          { label: "导入", id: "Import", prop: "Import", icon: "el-icon-upload2", isRowBtn: false },
          { label: "导出", id: "Export", prop: "Export", icon: "el-icon-download", isRowBtn: false },
          { label: "编辑", id: "Edit", prop: "Edit", isRowBtn: true },
          { label: "删除", id: "Delete", prop: "Delete", isRowBtn: true },
          { label: "详情", id: "Details", prop: "Details", isRowBtn: true },
        ],
        left: {
          title: "左侧树形",
          colField: "",
          dataType: "1",
          dataIdKey: "",
          dataPIdKey: "",
          dataValueKey: "",
          dataLabelKey: "",
          colNames: [], // 数据源字段列表
          options: [], // 静态数据
          dataCode: "",
        },
        table: {
          isPage: true,
          columns: [],
          customColumns: [],
          querys: [],
          sidx: "",
          isDESC: false,
          isKeyword: false,
        },
      },
      formData: {
        f_Type: 1,
        f_Code: "",
        f_Name: "",
        f_Icon: "el-icon-star-off",
        f_FormCode: "",
        f_FormVerison: "",
        f_PModuleId: "",
        f_ModuleId: "",
        f_SortCode: "",
        f_EnabledMark: 1,
        f_Description: "",
      },
      rules: {
        f_Code: [
          { required: true, message: "请输入编号", trigger: "blur" },
          {
            validator: this.lr_existDbFiled,
            keyValue: () => {
              return this.formData.f_ModuleId;
            },
            tableName: "lr_base_module",
            fieldName: "f_EnCode",
            keyName: "f_ModuleId",
            trigger: "null",
          },
        ],
        f_Name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        f_Icon: [{ required: true, message: "请选择图标", trigger: "blur" }],
        f_FormCode: [{ required: true, message: "请选择表单", trigger: "blur" }],
        f_FormVerison: [{ required: true, message: "请选择表单版本" }],
      },
      formScheme: null,
    };
  },
  asyncComputed: {
    formVerisons: {
      async get() {
        let res = [];
        if (!this.$validatenull(this.formData.f_FormCode)) {
          res = await this.$awaitWraper(api.getHistoryList(this.formData.f_FormCode));
        }
        return (res || []).map((t) => {
          return { label: this.lr_dateFormat(t.f_CreateDate), value: t.f_Id };
        });
      },
    },
  },
  computed: {
    ...mapGetters(["modulesExpandTree"]),
  },
  methods: {
    createUUID() {
      this.formData.f_Code = uuidv4();
    },
    steps(num) {
      return this.stepActive == num;
    },
    handleChangeLayoutType(type) {
      this.config.layoutType = type;
    },
    custmerformChange(val) {
      if (val == null) {
        this.formData.f_FormVerison = "";
      } else {
        this.formData.f_FormVerison = val.f_SchemeId;
      }
    },
    turnPropertysInfo(responseType) {
      let mainDbTables = [];
      let childDbTables = [];
      if (responseType.propertysInfo) {
        const mainData = responseType.propertysInfo.filter((item) => !item.propertysInfo.length);
        if (mainData.length) {
          //说明对象包含基本类型数据
          mainDbTables = mainData.map((item) => {
            return item.propertyName.toLowerCase();
          });
        }
        const childData = responseType.propertysInfo.filter((item) => item.propertysInfo.length);
        childDbTables = childData.flatMap((item) => {
          return item.propertysInfo.map((info) => {
            return info.propertyName.toLowerCase();
          });
        });
      }
      return mainDbTables.concat(childDbTables);
    },
    // 表单验证
    validateSteps() {
      return new Promise((resolve) => {
        this.$refs.baseInfo.validate(async (valid) => {
          if (valid) {
            const { f_Scheme } = (await this.$awaitWraper(api.getHistory(this.formData.f_FormVerison))) || {};

            this.formScheme = JSON.parse(f_Scheme);

            //表格所有字段列
            const apiIndex = this.formScheme.db.find((item) => item.apiType == 0);

            if (apiIndex) {
              const response = JSON.parse(apiIndex.f_ResponseType);
              this.tableFields = this.turnPropertysInfo(response);
            }

            if (this.formScheme.formType == 1) {
              // 如果是视图表单就关闭部分按钮
              this.config.btns = this.config.btns.filter((t) => ["Import", "Export", "Details"].includes(t.id));
            }

            const columns = [];
            this.formScheme.formInfo.tabList.forEach((tab) => {
              columns.push(
                ...tab.components.filter(
                  (t) =>
                    !["gridtable", "divider", "password", "viewtable", "card", "btn", "layerselect"].includes(t.type)
                )
              );
            });

            const colunmsMap = {};
            columns.forEach((item) => {
              colunmsMap[item.prop] = item;
            });

            this.columnsTree[0].children = columns.map((t) => {
              return {
                id: t.prop,
                prop: t.prop,
                field: t.field,
                label: t.label,
                type: t.type,
                width: 120,
                align: "left",
                isMinWidth: false,
                formField: t.field,
                formLabel: "",
                formValue: "",
                formEdit: false,
              };
            });

            // 1.获取表格列
            // 2.过滤掉已选列中在表格列中找不到的列
            let columnsChecked = this.config.table.columns.filter(
              (t) => this.columnsTree[0].children.findIndex((t2) => t2.prop == t.prop) != -1
            );
            columnsChecked.forEach((t) => {
              t.label = colunmsMap[t.prop].label;
            });

            this.config.table.columns = columnsChecked; //this.columnsTree[0].children.filter(t=>columnsChecked.findIndex(t2=>t2.prop == t.prop) != -1);

            this.queryTree[0].children = columns
              .filter((t) => !["upload", "uploadimg", "password", "timerange", "datetimerange"].includes(t.type))
              .map((t) => {
                return { id: t.prop, prop: t.prop, label: t.label };
              });
            let queryChecked = this.config.table.querys.filter(
              (t) => this.queryTree[0].children.findIndex((t2) => t2.prop == t.prop) != -1
            );
            queryChecked.forEach((t) => {
              t.label = colunmsMap[t.prop].label;
            });

            this.config.table.querys = queryChecked;

            this.colslist = columns.map((t) => {
              return { value: t.prop, label: t.label };
            });
            if (this.colslist.findIndex((t) => t.value == this.config.left.colField) == -1) {
              this.config.left.colField = "";
            }

            this.$nextTick(() => {
              this.$refs.columnsOp.setCheckedKeys(columnsChecked.map((t) => t.prop));
              this.$refs.queryOp.setCheckedKeys(queryChecked.map((t) => t.prop));
              this.$refs.btnOp.setCheckedKeys(this.config.btns.map((t) => t.id));
            });
          }
          resolve(valid);
        });
      });
    },

    // 表单方法
    resetForm() {
      this.formData.f_ModuleId = "";
      this.pageActiveName = "tab01";
      this.$refs.baseInfo && this.$refs.baseInfo.resetFields();
      this.config.layoutType = 1;
      this.config.queryType = "1";
      this.config.btns = [
        { label: "新增", id: "Add", prop: "Add", icon: "el-icon-plus", isRowBtn: false },
        { label: "导入", id: "Import", prop: "Import", icon: "el-icon-upload2", isRowBtn: false },
        { label: "导出", id: "Export", prop: "Export", icon: "el-icon-download", isRowBtn: false },
        { label: "编辑", id: "Edit", prop: "Edit", isRowBtn: true },
        { label: "删除", id: "Delete", prop: "Delete", isRowBtn: true },
        { label: "详情", id: "Details", prop: "Details", isRowBtn: true },
      ];
      this.config.left = {
        title: "左侧树形",
        colField: "",
        dataType: "1",
        dataIdKey: "",
        dataPIdKey: "",
        dataValueKey: "",
        dataLabelKey: "",
        colNames: [], // 数据源字段列表
        options: [], // 静态数据
        dataCode: "",
      };
      this.config.table = {
        isPage: true,
        columns: [],
        customColumns: [],
        querys: [],
        sidx: "",
        isDESC: false,
      };
    },
    setForm(data) {
      this.formData = data;
      const scheme = JSON.parse(data.f_Scheme);

      this.config.layoutType = scheme.layoutType;
      this.config.queryType = scheme.queryType;
      this.config.btns = scheme.btns;
      this.config.left = scheme.left;
      this.config.table = scheme.table;
    },
    getForm() {
      const postData = {};

      const formData = this.$deepClone(this.formData);
      formData.f_Scheme = JSON.stringify(this.$deepClone(this.config));

      postData.entity = formData;
      postData.moduleEntity = {
        f_EnCode: formData.f_Code,
        f_FullName: formData.f_Name,
        f_ParentId: formData.f_PModuleId,
        f_Icon: formData.f_Icon,
        f_Target: "custmerForm",
        f_IsMenu: 1,
        f_DeleteMark: 0,
        f_UrlAddress: `${formData.f_Code}`,
        f_EnabledMark: formData.f_EnabledMark,
        f_SortCode: formData.f_SortCode,
      };

      postData.moduleButtonEntitys = [];
      this.config.btns.forEach((btn) => {
        postData.moduleButtonEntitys.push({ f_EnCode: btn.prop, f_FullName: btn.label });
      });
      if (this.config.layoutType == 2 && this.config.left.dataType == "2") {
        postData.moduleButtonEntitys.push({ f_EnCode: "classifysSetting", f_FullName: "分类管理" });
      }

      const componentMap = {};
      postData.moduleFormEntitys = [];
      this.formScheme.formInfo.tabList.forEach((tab) => {
        tab.components.forEach((component) => {
          componentMap[component.prop] = component;
          if (!["gridtable", "divider", "card"].includes(component.type) && component.display) {
            postData.moduleFormEntitys.push({ f_EnCode: component.prop, f_FullName: component.label });
          } else if (["gridtable"].includes(component.type)) {
            postData.moduleFormEntitys.push(
              ...component.children.map((t) => {
                return {
                  f_EnCode: `${component.prop}|${t.prop}`,
                  f_FullName: `${component.label || "表格"}-${t.label}`,
                };
              })
            );

            postData.moduleFormEntitys.push({
              f_EnCode: `${component.prop}_add`,
              f_FullName: `${component.label || "表格"}-添加按钮`,
            });

            postData.moduleFormEntitys.push({
              f_EnCode: `${component.prop}_remove`,
              f_FullName: `${component.label || "表格"}-删除按钮`,
            });
          } else if (["divider"].includes(component.type)) {
            postData.moduleFormEntitys.push({
              f_EnCode: component.prop,
              f_FullName: `${component.label}-${component.html}`,
            });
          }
        });
      });

      postData.moduleColumnEntitys = [];
      this.config.table.columns.forEach((column) => {
        const columnComponent = componentMap[column.prop];
        const enCode = `${columnComponent.field}${
          this.formScheme.formType == 0 ? this.formScheme.db.findIndex((t) => t.name == columnComponent.table) : ""
        }`;

        postData.moduleColumnEntitys.push({ f_EnCode: enCode, f_FullName: column.label });
      });

      if (this.config.table.customColumns) {
        this.config.table.customColumns.forEach((column) => {
          postData.moduleColumnEntitys.push({ f_EnCode: column.field, f_FullName: column.label });
        });
      }

      return postData;
    },
  },
};
</script>
